package com.ext.aic.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.recyclerview.widget.GridLayoutManager;

import com.ext.aic.R;
import com.ext.aic.adapter.NinePictureAdapter;
import com.ext.aic.beans.Attachment;
import com.ext.aic.databinding.NinePictureViewBinding;
import com.ext.aic.enums.EditNineSource;
import com.eyinfo.android_pure_utils.utils.PixelUtils;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;

import java.util.List;

import lombok.Setter;

public class NinePictureFragment extends BaseFragment {

    private NinePictureViewBinding binding;
    private int maxWidth;
    private boolean onlyPreview;
    @Setter
    private List<Attachment> attachments;
    @Setter
    private EditNineSource nineSource;

    private NinePictureAdapter adapter;

    public NinePictureFragment(int maxWidth, boolean onlyPreview) {
        this.maxWidth = maxWidth;
        this.onlyPreview = onlyPreview;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.nine_picture_view, container, false);
        binding = NinePictureViewBinding.bind(view);
        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        binding.imagesRv.setLayoutManager(new GridLayoutManager(getContext(), 3));
        int spacing = PixelUtils.dip2px(getContext(), 4);
        binding.imagesRv.addItemDecoration(new GridSpacingItemDecoration(3, spacing, true));
        adapter = new NinePictureAdapter(getContext(), maxWidth, onlyPreview);
        adapter.setAttachments(attachments);
        adapter.setNineSource(nineSource);
        binding.imagesRv.setAdapter(adapter);
    }

    @SuppressLint("NotifyDataSetChanged")
    public void bindAttachmentDataEvent(List<Attachment> attachments) {
        this.attachments = attachments;
        //存在加载顺序的问题（onViewCreated和bindAttachmentDataEvent先后执行问题）
        if (adapter != null) {
            adapter.setAttachments(attachments);
            adapter.notifyDataSetChanged();
        }
    }
}
